package main

import (
    "fmt"
    "io/ioutil"
    "encoding/json"
    "os"
    "sync"
)

type SSHProxy struct {
    mu           sync.RWMutex
    registryPath string            `json:"-"`
    PemFilePath  string             `json:"pem_path"` //ssh加密使用
    Salt         string             `json:"salt"`     //不保存文本的密码
    AppInfos     map[string]AppInfo `json:"app_map"`
    Port         string                `json:"port"`
}

func (dp *SSHProxy) RegClientKey(appid, client, pk string) {
    dp.mu.Lock()
    defer dp.mu.Unlock()
    dp.AppInfos[appid].TrustedClientKeys[client] = pk
    dp.save()
}

func (dp *SSHProxy) Load() error {
    dp.mu.Lock()
    defer dp.mu.Unlock()
    f := dp.registryPath
    content, err := ioutil.ReadFile(f)
    if err != nil {
        return err
    }
    err = json.Unmarshal(content, dp)
    if err != nil {
        return err
    }
    dp.registryPath = f
    if dp.PemFilePath == "" {
        return fmt.Errorf("missing pem")
    }
    if dp.Port == "" {
        return fmt.Errorf("missing port")
    }
    return nil
}

func NewSSHProxy(f string) (*SSHProxy, error) {
    proxy := &SSHProxy{}
    proxy.registryPath = f
    err := proxy.Load()
    return proxy, err
}

func (dp *SSHProxy) save() error {
    content, err := json.Marshal(dp)
    if err != nil {
        return err
    }
    if err := ioutil.WriteFile(dp.registryPath+".tmp", content, os.FileMode(0644)); err != nil {
        return err
    }
    if err := os.Rename(dp.registryPath+".tmp", dp.registryPath); err != nil {
        return err
    }
    return nil
}

func main() {
    p, err := NewSSHProxy("testdata/reg.json")
    if err == nil {
        //定时save 或者load一次？
        fmt.Println(p.serve())
    }
}

/*
Step 1. Create key (password protected)
openssl genrsa -out prvtkey.pem 1024/2038                     (with out password protected)
openssl genrsa -out dummy-genrsa.pem 2048
*/
